//
//  NewMenuTab.m
//  Qianbao
//
//  Created by zhangtie on 13-12-16.
//  Copyright (c) 2013年 qianwang365. All rights reserved.
//

#import "NewMenuTab.h"
#import "CustomTabModel.h"

#define INVALIDCOUNT    -1

@interface NewMenuTab ()<CustomTabItem_Delegate, UIScrollViewDelegate>
{
    UIImageView     *_imageSign;
    
    NSInteger       _ncurrentPage;  //当前body的page
    
    NSInteger       _nscreenCount;  //一屏幕显示menu标题的数量，用于滚蛋时候设置menuhead的内容偏移
}

@property(nonatomic, retain)UIScrollView    *menuHead;
@property(nonatomic, retain)UIScrollView    *menuBody;

@end

@implementation NewMenuTab

- (void)dealloc
{
    RELEASE_SAFELY(_imageSignName);
    RELEASE_SAFELY(_menus);
    RELEASE_SAFELY(_color_normal);
    RELEASE_SAFELY(_color_selected);
    RELEASE_SAFELY(_color_textNormal);
    RELEASE_SAFELY(_color_textSelected);
    RELEASE_SAFELY(_menuHead);
    RELEASE_SAFELY(_menuBody);
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.imageSignName = @"sign.png";
        self.menuHeadHeight = kMENUHEADHEIGHT;
        self.font_size      = 15;
        self.itemSpace      = 0;
        self.orginY         = 2;
        _ncurrentPage       = 0;
        _nscreenCount       = INVALIDCOUNT;
        _canMove            = YES;
        _isNeedSpanLine     = YES;
        _menuLayout         = MENULAYOUT_DEFAULT;
        _showSignImage      = YES;
    }
    return self;
}

/**
 descrtion:获取某个item标题
 @parm: item:要获取标题的item
 @returns:返回参数item的标题
 add by zt 2013-4-3
 @exception:
 */
- (NSString*)getTitleForItem:(CustomTabItem_DataItem*)item
{
    if(!item)
        return @"";
    
    if(item.data_type == DATA_TYPE_VALUE)
        return item.item_data;
    else
    {
        if(item.key_data)
        {
            if(item.item_data && [item.item_data count]>0)
                return [item.item_data objectForKey:item.key_data];
        }
    }
    return @"";
}
- (void)layoutSubviews{
    [super layoutSubviews];
    [self layoutIfNeeded];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    
    if(!self.menus ||
       [self.menus count] <= 0)
        return;
    

    REMOVEALLSUBVIEW(self.menuHead);
    
    [self addSubview:self.menuBody];
    REMOVEALLSUBVIEW(self.menuBody);
    
    _ncurrentPage       = _ndefaultSelectedIndex;
    
    NSInteger ndataCount = [self.menus count];
    
    //计算每个tabItem的frame
    CGFloat totalWidth = GetWidth(self);
    CGFloat item_width = 0;
    if(self.isCoverage)
        item_width = (totalWidth - _itemSpace*(ndataCount + 1))/ndataCount;//floorf((totalWidth - _itemSpace*(ndataCount + 1))/ndataCount);
    else
        item_width = self.itemWidth;
    
    CGFloat headItem_orginX = 0;
    CGFloat headItem_orginY = 0.0f;
    CGFloat headItem_height = self.menuHeadHeight - headItem_orginY*2;
    
    CGFloat headContentWidth = 0.0f;
    CGFloat bodyContentWidth = ndataCount * GetWidth(self);
    
    CGFloat bodyItem_orginX = 0;
    
    for (NSInteger i=0; i < ndataCount; ++i)
    {
        //head
        CGFloat headItemWidth   = 0;
        CustomTabItem_DataItem *data_item = [self.menus objectAtIndex:i];
        NSString* str_title     = [self getTitleForItem:data_item];
        if(item_width == 0)
        {
            CGSize textSize     = [str_title sizeWithFont:FONT_TITLE(self.font_size)];
            headItemWidth       = textSize.width + 22;
        }
        else
        {
            headItemWidth   = item_width;
        }
        
        CGRect item_frame   = CGRectMake(headItem_orginX, headItem_orginY, headItemWidth, headItem_height);
        CustomTabItem* item = _ALLOC_OBJ_WITHFRAME_(CustomTabItem, item_frame);
        item.color_normal   = self.color_normal; //[QBUtil getColor:@"FCFCFC"];
        item.color_selected = self.color_selected;//[QBUtil getColor:@"FCFCFC"];
        if(!self.color_textSelected)
        {
            item.color_textSelected = [UIColor orangeColor];
        }
        else
        {
            item.color_textSelected = self.color_textSelected;
        }
        if(!self.color_textNormal)
        {
            item.color_textNormal   = [UIColor lightGrayColor];
        }
        else
        {
            item.color_textNormal   = self.color_textNormal;
        }
        [item setFontSize:self.font_size];
        item.tabItem_delegate = self;
        [item setIndex:i];
        [self.menuHead addSubview:item];
        
        //设置标题
        if(str_title)
            [item setTabItemTitle:str_title];
        
        if(self.isNeedSpanLine)
        {
            //添加分隔线
            if(i != (ndataCount-1))
            {//不是最后就不添加分隔
                CGSize fontSize = [str_title sizeWithFont:FONT_TITLE(self.font_size)];
                CGFloat span_height = fontSize.height - 5;
                CGFloat span_orginX = item_frame.origin.x + item_frame.size.width - SPAN_WIDTH;
                CGFloat span_orginY = (item_frame.size.height - span_height)/2;
                CGFloat span_width  = SPAN_WIDTH;
                CGRect span_frame = CGRectMake(span_orginX, span_orginY, span_width, span_height);
                UILabel *lab_span = _ALLOC_OBJ_WITHFRAME_(UILabel, span_frame);
                [lab_span setBackgroundColor:[UIColor lightGrayColor]];
                [self.menuHead addSubview:lab_span];
                RELEASE_SAFELY(lab_span);
            }
        }
        
        //body
        UIView *itemView = [data_item.item_data objectForKey:KEY_DATAVIEW];
        CGRect viewFrame = itemView.frame;
        viewFrame.origin.x = bodyItem_orginX;
        itemView.frame   = viewFrame;
        
        //设置默认选中项
        if(i == _ndefaultSelectedIndex)
        {
           
            [item changeForState:TABITEM_STATE_SELECTED];
            [self setSignImageCenterForItem:item];
            if(self.isNeedDefaultSelectedEvent)
            {
                [self toNextResponderWithObject:item];
            }
            else
            {
                 [self.menuBody addSubview:itemView];
            }
        }
        else
        {
            [item changeForState:TABITEM_STATE_NORMAL];
        }
        RELEASE_SAFELY(item);
        
        headContentWidth += headItemWidth;
        headItem_orginX  += headItemWidth;
        
        
        bodyItem_orginX  += GetWidth(self.menuBody);
        if(headContentWidth >= GetWidth(self.menuHead))
        {
            _nscreenCount = i;
        }
    }
    
    
    [self.menuHead setContentSize:CGSizeMake(headContentWidth, self.menuHeadHeight)];
    [self.menuBody setContentSize:CGSizeMake(bodyContentWidth, GetHeight(self.menuBody))];
    
    [self.menuBody setScrollEnabled:self.canMove];
//    if(self.canMove)
    {
        CGFloat contentOffsetX = GetWidth(self) * _ncurrentPage;
        [self.menuBody setContentOffset:CGPointMake(contentOffsetX, 0) animated:YES];
    }
    
    [self addSubview:self.menuHead];
}

- (void)initImageSign
{
    if(self.showSignImage)
    {
        if(!_imageSign)
        {
            _imageSign = [[UIImageView alloc]initWithImage:IMGNAMED(self.imageSignName)];
            _imageSign.backgroundColor = [UIColor flatDarkBlackColor];
            [self.menuHead addSubview:_imageSign];
            //        SIMPLE_SAFERELEASE(_imageSign);
        }
    }
}

//显示与隐藏menuhead
- (void)setMenuHeadVisible:(BOOL)bshow
{
    [self.menuHead setHidden:!bshow];
}

/**
 @descrtion:    根据index设置菜单head选中状态
 @parm:         index:即将设置选中的index
 @returns:      返回当前选中的item
 add by zt 2013-12-16
 @exception:
 */
- (CustomTabItem*)setMeunItemHeadSelectedAtIndex:(NSInteger)index
{
    CustomTabItem *selectedItem = nil;
    NSArray *subViews = [self.menuHead subviews];
    for (UIView *view in subViews)
    {
        if([view isKindOfClass:[CustomTabItem class]])
        {
            CustomTabItem *item = (CustomTabItem*)view;
            if(item.nindex == index)
            {
                [item changeForState:TABITEM_STATE_SELECTED];
                [self setSignImageCenterForItem:item animal:YES];
                selectedItem = item;
            }
            else
            {
                [item changeForState:TABITEM_STATE_NORMAL];
            }
        }
        else
            continue;
    }
    
    return selectedItem;
}

/**
 @descrtion:    根据index获取item对应的view
 @parm:         index:获取的index索引
 @returns:      返回对应的view
 add by zt 2014-1-21
 @exception:
 */
- (UIView*)viewAtIndex:(NSInteger)index
{
    if(index < 0 ||
       index > [self.menus count])
    {
        return nil;
    }
    
    CustomTabItem_DataItem *item = [self.menus objectAtIndex:index];
    return [item.item_data objectForKey:KEY_DATAVIEW];
}

- (void)setSignImageCenterForItem:(CustomTabItem*)item
{
    [self setSignImageCenterForItem:item animal:NO];
}

- (void)setSignImageCenterForItem:(CustomTabItem*)item animal:(BOOL)animal
{
    if(!_imageSign)
        [self initImageSign];
    
    UIImage *image       = IMGNAMED(@"bg_menu_bottom.png");
    CGSize imageSize     = image.size;
    if(animal)
    {
        _ANIMATIONS_INIT_BEGIN_(0.3);
        _imageSign.center = CGPointMake(item.center.x, GetHeight(item)- imageSize.height + 7);
        _ANIMATIONS_INIT_END_;
    }
    else
    {
        _imageSign.center = CGPointMake(item.center.x, GetHeight(item)  - imageSize.height + 7);
    }
    [self.menuHead bringSubviewToFront:_imageSign];
}

- (void)setMenuItemSelectedAtIndex:(NSInteger)index
{
    if(index >= [self.menus count])
    {
        return;
    }
    
    [self changeIndexDoForIndex:index];
}

#pragma mark -- TabItemDelegate
- (void)doTabItemClick:(id)sender
{
    if(!_imageSign)
        [self initImageSign];
    
    CustomTabItem* cur_item = (CustomTabItem*)sender;
    
    if(_ncurrentPage == cur_item.nindex)//过滤操作
        return;
    
    [self changeIndexDoForIndex:cur_item.nindex];
}

/**
 @descrtion:    当前pageindex 发生变化时候触发事件
 @parm:         itemIndex:当前变化的最终的index
 add by zt 2013-12-
 @exception:
 */
- (void)changeIndexDoForIndex:(NSInteger)itemIndex
{
    _ncurrentPage = itemIndex;
    
    CustomTabItem *item = [self setMeunItemHeadSelectedAtIndex:itemIndex];
    [self checkMenuHeadOffset:item];
    CGFloat orginX = itemIndex * GetWidth(self.menuBody);
    [self.menuBody setContentOffset:CGPointMake(orginX, 0) animated:YES];

    [self toNextResponderWithObject:item];
}

- (BOOL)isBodyContainView:(UIView*)subView
{
    NSArray *subViews = self.menuBody.subviews;
    return [subViews containsObject:subView];
}

- (void)addSubviewToBody:(UIView*)subView
{
    [self.menuBody addSubview:subView];
}

/**
 descrtion:事件交给下个处理者
 @parm: parm:这里传递对应的item
 @returns:
 add by zt 2013-4-7
 @exception:
 */
- (void)toNextResponderWithObject:(id)parm
{//交给上层视图或者控制器处理
    if(_delegate && [_delegate respondsToSelector:@selector(doTabItemClick:withItem:)])
        [_delegate performSelector:@selector(doTabItemClick:withItem:) withObject:self withObject:parm];
}

- (void)checkMenuHeadOffset:(CustomTabItem*)itemSelected
{
    if(!self.isCoverage)
    {
        if((_ncurrentPage + 1) >= _nscreenCount)
        {
            [self.menuHead setContentOffset:CGPointMake(GetWidth(itemSelected) + GetOriginX(itemSelected) - GetWidth(self.menuHead), 0) animated:YES];
        }
        if(_ncurrentPage == 0)
        {
            [self.menuHead setContentOffset:CGPointZero animated:YES];
        }
    }
}

#pragma mark -- UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(!_canMove)   //不能手动拖则立即返回
        return;
    
    CGFloat pageWidth   = scrollView.frame.size.width;
    NSInteger pageIndex = floor((scrollView.contentOffset.x - pageWidth /2) / pageWidth) +1;
    if(pageIndex == _ncurrentPage)
        return;
    
    _ncurrentPage = pageIndex;
    
    CustomTabItem *itemSelected = [self setMeunItemHeadSelectedAtIndex:_ncurrentPage];
    [self checkMenuHeadOffset:itemSelected];
    
    [self changeIndexDoForIndex:_ncurrentPage];
}

#pragma mark -- getter
- (UIScrollView*)menuHead
{
    if(!_menuHead)
    {
        CGRect contentRect      = self.bounds;
        contentRect.size.height = self.menuHeadHeight;
        _menuHead = _ALLOC_OBJ_WITHFRAME_(UIScrollView, contentRect);
        [_menuHead setBackgroundColor:[UIColor whiteColor]];
        [_menuHead setShowsHorizontalScrollIndicator:NO];
        [_menuHead setShowsVerticalScrollIndicator:NO];
    }
    return _menuHead;
}

- (UIScrollView*)menuBody
{
    if(!_menuBody)
    {
        CGRect contentRect      = self.bounds;
        if(self.menuLayout == MENULAYOUT_DEFAULT)
        {
            contentRect.origin.y    = self.menuHeadHeight;
            contentRect.size.height = GetHeight(self) - self.menuHeadHeight - GetOriginY(self.menuHead);
        }
        _menuBody = _ALLOC_OBJ_WITHFRAME_(UIScrollView, contentRect);
        _menuBody.delegate      = self;
        _menuBody.pagingEnabled = YES;
        [_menuBody setBackgroundColor:[UIColor clearColor]];
        [_menuBody setShowsHorizontalScrollIndicator:NO];
        [_menuBody setShowsVerticalScrollIndicator:NO];
    }
    
    return _menuBody;
}

- (NSInteger)ncurrentSelectedIndex
{
    return _ncurrentPage;
}

- (CGRect)viewFrame
{
    if(self.menuLayout == MENULAYOUT_DEFAULT)
    {
        return CGRectMake(0, self.orginY, GetWidth(self.menuBody), GetHeight(self.menuBody) - self.orginY);
    }
    else
    {
        return self.bounds;
    }
}


@end
